<script setup>
import {inject, reactive, ref} from 'vue'
import {useRouter} from 'vue-router'
import axios from 'axios'
import {ElMessage} from 'element-plus'

const getPath = inject('getPath')

const router = useRouter()

const ruleFormRef = ref()
// 保存输入框输入的内容
const ruleForm = reactive({
  no: '',
  password: ''
})

// 验证账户
const validatNo = (rule, value, callback) => {
  let regx = /[\u4e00-\u9fa5_a-zA-Z_]{1,10}$/
  if (value === '') {
    callback(new Error('账号不能为空'))
  } else if (regx.test(value) == false) {
    callback(new Error('请输入正确的账号'))
  } else {
    callback()
  }
}

// 验证密码
const validatePass = (rule, value, callback) => {
  var regx = /^[A-Za-z0-9]\w{5,15}$/
  if (value === '') {
    callback(new Error('密码不能为空'))
  } else if (regx.test(value) == false) {
    callback(new Error('请输入正确的密码格式（6到16位有字母数字组成）'))
  } else {
    callback()
  }
}


// 给输入框添加验证
const rules = reactive({
  no: [{validator: validatNo, trigger: 'blur'}],
  password: [{validator: validatePass, trigger: 'blur'}],
})

const submitForm = (formEl) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      // 输入框验证通过 可以发起登录请求
      axios.post(`${getPath}login`, ruleForm).then(res => {
        if (res.data.code == 200) {
          ElMessage({
            message: res.data.msg,
            type: 'success',
          })
          // 将token保存到本地
          localStorage.setItem('token', res.data.token)
          localStorage.setItem('id', res.data.data.id)
          localStorage.setItem('roleId', (res.data.data.roleId === 0 ? '超级管理员' : (res.data.data.roleId === 1 ? '管理员' : '普通账号')))
          router.push('/')
        } else {
          ElMessage({
            message: res.data.msg,
            type: 'error',
          })
        }
      })
      console.log('submit!')

    } else {
      console.log('error submit!')
    }
  })
}


const goRegister = () => {
  // 跳转注册页面
  console.log(router);
  router.push('/register')
}

</script>
<template>
  <div class="login">
    <div class="login-bg">
      <div class="login-form">
        <div class="logo">
          <img src="../assets/login.webp" alt="">
        </div>
        <div class="form-box">
          <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" status-icon :rules="rules"
                   label-width="auto" class="demo-ruleForm">

            <el-form-item label="账号" prop="no">
              <el-input v-model="ruleForm.no" autocomplete="off" placeholder="请输入账号"/>
            </el-form-item>

            <el-form-item label="密码" prop="password">
              <el-input v-model="ruleForm.password" type="password" autocomplete="off" placeholder="请输入密码"/>
            </el-form-item>


            <el-form-item>
              <el-button type="primary" @click="submitForm(ruleFormRef)">
                立即登录
              </el-button>
              <el-button @click="goRegister">去注册</el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>
  </div>
</template>
<style scoped>
img {
  width: 100%;
  height: 100%;
}

.login-bg {
  width: 100%;
  height: 928px;
  background-image: url('../assets/bg.jpeg');
  background-repeat: no-repeat;
  background-size: 100%;
  display: flex;
  align-items: center;
}

.login-form {
  width: 600px;
  height: 350px;
  background-color: white;
  margin: 0 auto;
  display: flex;
  align-items: center;
  box-shadow: 0 2px 10px rgba(0, 0, 0, .15);
  border-radius: 40px;
  background-color: gray;
  background-image: linear-gradient(to right, black, gray);
}

.logo {
  width: 124px;
  height: 200px;
  margin-left: 50px;
  margin-right: 50px;
}
</style>